package com.spt.security.ctrl;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.spt.security.dao.IShiroUser;  
  
@Controller  
@RequestMapping("/security")  
public class UserController {
    
    private static final Gson gson = new Gson();
    private static Logger log = LogManager.getLogger("com.spt.ws.man");
    @Autowired
    IShiroUser userService;
    
    
    
    @RequestMapping(value="/getUsers")  
    @RequiresRoles(value={"ADMIN"},logical=Logical.OR)
    public @ResponseBody String getUsers(HttpServletRequest request){ 
        Map<String,Object> out = Maps.newHashMap();
        List<Map<String, Object>> li = userService.getUsers();
        out.put("code", "0");
        out.put("data", li);
        return gson.toJson(out);  
    }  
    
    
    @RequestMapping(value = "/modifyUser")
    @RequiresRoles(value={"ADMIN"},logical=Logical.OR)
    public @ResponseBody String modify(HttpServletRequest req, Model model) {
        Enumeration<String> a = req.getParameterNames();
        Map<String, String> param = Maps.newHashMap();
        while(a.hasMoreElements()){
            String key = a.nextElement();
            param.put(key, req.getParameter(key));
        }
        Map<String, Object> user = (Map<String, Object>) req.getSession().getAttribute("currentUser");
        
        Map<String,Object> out = new HashMap<String, Object>();
        
        param.put("creator", (String) user.get("USERNAME"));
        Map<String, Object> rtRow;
        try {
            if(param.get("isNewRecord") != null) {
                rtRow = userService.addUser(param);
            }else {
                rtRow = userService.modifyUserRoles(param);
            }
            out.put("code", "0");
            out.put("returnData", rtRow);
            out.put("msg", gson.toJson(out));
        } catch (Exception e) {
            out.put("code", "-1");
            out.put("msg", e.getMessage());
            out.put("msg", gson.toJson(out));
        }
        
        return gson.toJson(out);
    }
    
    @RequestMapping(value="/delUser")  
    @RequiresRoles(value={"ADMIN"},logical=Logical.OR)
    public @ResponseBody String del(HttpServletRequest request){ 
        Map<String,Object> out = Maps.newHashMap();
        String userId = request.getParameter("id");
        try {
            userService.delUser(userId);
            out.put("code", "0");
        } catch (Exception e) {
            out.put("code", "-1");
            log.error(e.getMessage());
        }
        
        return gson.toJson(out);  
    }
    
    @RequestMapping(value="/chgpasswd")  
    @RequiresRoles(value={"ADMIN"},logical=Logical.OR)
    public @ResponseBody  String chgPasswd(HttpServletRequest request){ 
        Map<String,Object> out = Maps.newHashMap();
        String oldPasswd = request.getParameter("oldPasswd");
        String newPasswd = request.getParameter("newPasswd");
        Map<String, Object> user = (Map<String, Object>) request.getSession().getAttribute("currentUser");
        try {
            userService.modifyPasswd(oldPasswd, newPasswd, (String) user.get("USERNAME"));
            out.put("code", "0");
            //out.put("message", "操作成功：" userName + " 已被删除");
        } catch (Exception e) {
            out.put("code", "-1");
            log.error(e.getMessage());
        }
        
        return gson.toJson(out);  
    }
    
    @RequestMapping(value="/resetPasswd")  
    @RequiresRoles(value={"ADMIN"},logical=Logical.OR)
    public @ResponseBody String resetPasswd(HttpServletRequest request){ 
        Map<String,Object> out = Maps.newHashMap();
        String userName = request.getParameter("userName");
        try {
            userService.resetPasswd(userName);
            out.put("code", "0");
        } catch (Exception e) {
            out.put("code", "-1");
            out.put("message", e.getMessage());
            log.error(e.getMessage());
        }
        
        return gson.toJson(out);  
    }

    
    @RequestMapping(value="/modifyRoles")  
    @RequiresRoles(value={"ADMIN"},logical=Logical.OR)
    public @ResponseBody String modifyRoles(HttpServletRequest request){ 
        String rows = request.getParameter("rows");
        /*String deleteRows = req.getParameter("deleterows");
        String modifytRows = req.getParameter("modifyrows");*/
        
        Map<String, Object> user = (Map<String, Object>) request.getSession().getAttribute("currentUser");
        
        Map<String,Object> out = new HashMap<String, Object>();
        String messager = "";
        if(rows != null ){
            List<Map<String, String>> li = gson.fromJson(rows, List.class);
            if(li.size()>0){
                for(Map<String, String> params : li){
                    try {
                        params.put("creator", (String) user.get("USERNAME"));
                        userService.modifyUserRoles(params);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        messager += "失败信息：" + e.getMessage() + "<br>";
                    }
                }
            }
        }
        /*if(modifytRows != null ){
            List<Map<String, String>> li = gson.fromJson(modifytRows, List.class);
            if(li.size()>0){
                for(Map<String, String> params : li){
                    try {
                        taskService.modifyTask(params);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error(e.getMessage());
                        messager += "失败信息：taskid " + params.get("TASKID") + ", groupid " + params.get("GROUPID") + "更新失败。<br>";
                    }
                }
            }
        }*/
        
        /*if(deleteRows != null ){
            List<Map<String, String>> li = gson.fromJson(deleteRows, List.class);
            if(li.size()>0){
                for(Map<String, String> params : li){
                    try {
                        taskService.removeTask(params.get("ID"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error(e.getMessage());
                        messager += "失败信息：taskid " + params.get("TASKID") + ", groupid " + params.get("GROUPID") + "更新失败。<br>";
                    }
                }
            }
        }*/
        if(messager.length() == 0){
            out.put("code", "0");
        }else{
            out.put("code", "-1");
            out.put("message", messager);
        }
        
        return gson.toJson(out);
    }
}  
